package huffmanCode;

import java.util.*;

public class HuffmanCode {
    public static void main(String[] args) {
        String content = "i like like like java do you like a java";
        byte[] bytes = content.getBytes();

        byte[] huffmanZip = huffmanZip(bytes);
        System.out.println("huffmanZip");
        System.out.println(Arrays.toString(huffmanZip));
     /*   ArrayList<Node> nodes = getNodes(bytes);
        Node huffmanCode = createHuffmanCode(nodes);
        getCodes(huffmanCode, "", stringBuilder);
        byte[] bytes1 = zip(bytes);
        System.out.println(bytes1.length);
        System.out.println(Arrays.toString(bytes1));*/
    }

    private static byte[] decode(byte[] huffmanBytes) {
        StringBuilder stringBuilder1 = new StringBuilder();
        for (int i = 0; i < huffmanBytes.length; i++) {
            byte b = huffmanBytes[i];
            boolean flag = (i == huffmanBytes.length - 1);
            stringBuilder1.append(byteToBitString(!flag, b));
        }
        HashMap<String, Byte> map = new HashMap<>();
        for (Map.Entry<Byte, String> entry : huffmanCodes.entrySet()) {
            map.put(entry.getValue(), entry.getKey());
        }
        ArrayList<Byte> list = new ArrayList<>();
        for (int i = 0; i < stringBuilder1.length(); ) {
            int count = 1;
            boolean flag = true;
            Byte b = null;
            while (flag) {
                String key = stringBuilder1.substring(i, count + i);
                b = map.get(key);
                if (b == null) {
                    count++;
                } else {
                    flag = false;
                }
            }
            list.add(b);
            i += count;
        }
        byte b[] = new byte[list.size()];
        for (int i = 0 ; i < b.length; i++){
            b[i] = list.get(i);
        }
        return b;
    }


    public static String byteToBitString(boolean flag, byte b) {
        //使用变量保存b
        int temp = b;//将b转成int
        //如果是正数我们还存在补高位
        if (flag) {
            temp |= 256;

        }
        String str = Integer.toBinaryString(temp);
        if (flag) {
            return str.substring(str.length() - 8);
        } else {
            return str;
        }
    }

    public static byte[] huffmanZip(byte[] bytes) {
        ArrayList<Node> nodes = getNodes(bytes);
        Node huffmanCode = createHuffmanCode(nodes);
        getCodes(huffmanCode, "", stringBuilder);
        return zip(bytes);
    }

    public static byte[] zip(byte[] bytes) {
        StringBuilder stringBuilder1 = new StringBuilder();
        //把数组的字符串替换成哈夫曼编码存储
        for (byte b : bytes) {
            stringBuilder1.append(huffmanCodes.get(b));
        }
        //判断是否能被8整除
        int len = 0;//表示最终压缩的字节大小
        if (stringBuilder1.length() % 8 == 0) {
            len = stringBuilder1.length() / 8;
        } else {
            len = stringBuilder1.length() / 8 + 1;
        }
        byte[] huffmanCodeBytes = new byte[len];
        int index = 0;
        for (int i = 0; i < stringBuilder1.length(); i += 8) {
            String substring;
            if (i + 8 > stringBuilder1.length()) {
                substring = stringBuilder1.substring(i, stringBuilder1.length());
            } else {
                substring = stringBuilder1.substring(i, i + 8);
            }
            huffmanCodeBytes[index] = (byte) Integer.parseInt(substring, 2);
            index++;
        }
        return huffmanCodeBytes;
    }

    static StringBuilder stringBuilder = new StringBuilder();
    static HashMap<Byte, String> huffmanCodes = new HashMap<>();

    /**
     * 获取哈夫曼编码表
     *
     * @param node          节点
     * @param code          当前节点是左还是右 左0右1
     * @param stringBuilder
     */
    public static void getCodes(Node node, String code, StringBuilder stringBuilder) {
        StringBuilder stringBuilder2 = new StringBuilder(stringBuilder);
        stringBuilder2.append(code);
        if (node != null) {
            //当前节点不是叶子节点
            if (node.data == null) {
                getCodes(node.left, "0", stringBuilder2);
                getCodes(node.right, "1", stringBuilder2);
            } else {
                huffmanCodes.put(node.data, stringBuilder2.toString());
            }
        }
    }

    /**
     * 创建哈夫曼树
     *
     * @param nodes
     * @return
     */
    public static Node createHuffmanCode(ArrayList<Node> nodes) {
        while (nodes.size() > 1) {
            Collections.sort(nodes);
            Node leftNode = nodes.get(0);
            Node rightNode = nodes.get(1);
            Node parent = new Node(null, leftNode.weight + rightNode.weight);
            parent.left = leftNode;
            parent.right = rightNode;
            nodes.remove(leftNode);
            nodes.remove(rightNode);
            nodes.add(parent);
        }
        return nodes.get(0);
    }


    /**
     * 获取
     *
     * @param bytes
     * @return
     */
    public static ArrayList<Node> getNodes(byte[] bytes) {
        //创建一个集合，存储Node
        ArrayList<Node> nodes = new ArrayList<>();
        HashMap<Byte, Integer> map = new HashMap<>();
        for (byte b : bytes) {
            Integer count = map.get(b);
            if (count == null) {
                //说明这个字节没有出现过
                map.put(b, 1);
            } else {
                map.put(b, count + 1);
            }
        }
        for (Map.Entry<Byte, Integer> entry : map.entrySet()) {
            nodes.add(new Node(entry.getKey(), entry.getValue()));
        }
        return nodes;
    }
}

class Node implements Comparable<Node> {

    Byte data;
    int weight;
    Node left;
    Node right;

    public Node(Byte data, int weight) {
        this.data = data;
        this.weight = weight;
    }

    public void preOrder() {
        if (this.left == null && this.right == null) {
            System.out.println(this);
        }
        if (this.left != null) {
            this.left.preOrder();
        }
        if (this.right != null) {
            this.right.preOrder();
        }
    }

    @Override
    public String toString() {
        return "Node{" +
                "data=" + data +
                ", weight=" + weight +
                '}';
    }

    @Override
    public int compareTo(Node o) {
        return this.weight - o.weight;
    }
}
